//
//  LCHtmlController.m
//  LCHtmlController
//
//  Created by jiukuyinyue on 2017/8/25.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LCHtmlController.h"

@interface LCHtmlController () 

@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, assign) CGFloat delayTime;
@property (nonatomic, assign) CGFloat contentHeight;
@end

@implementation LCHtmlController

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"调转链接 %@",_link);
    [self setupRefresh];
    [self setupWebView];
    [self setupProgressView];
}
-(void)setupRefresh{
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    _scrollView = scrollView;
    [self.view addSubview:scrollView];
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    MJRefreshGifHeader *refreshGifHeader = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // 隐藏时间
    refreshGifHeader.lastUpdatedTimeLabel.hidden = YES;
    // 设置header
    self.scrollView.mj_header = refreshGifHeader;
}
-(void)loadNewData{
    Reachability *reach = [Reachability reachabilityWithHostName:@"http://baidu.com"];
    if ([reach currentReachabilityStatus] == NotReachable){
        [SVProgressHUD showErrorWithStatus:NoNetwork];
        [SVProgressHUD dismissWithDelay:0.5];
        [self.scrollView.mj_header endRefreshing];
    }else{
        [_webView reload];
    }
}
-(void)setupWebView{
    // 根据生成的WKUserScript对象，初始化WKWebViewConfiguration
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 145 - 8 - HOME_INDICATOR_HEIGHT - NAVIGATION_BAR_HEIGHT + 64) configuration:config];
    _webView.allowsBackForwardNavigationGestures = YES;//是否允许左右划手势导航,默认不允许
    [self.scrollView addSubview:_webView];
    _webView.scrollView.bounces = NO;//禁止WebView滚动和回弹方法
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",_link]];//goURLStrings[index]]];//创建URL
    NSURLRequest* request = [NSURLRequest requestWithURL:url];//创建NSURLRequest
    [_webView loadRequest:request];//加载
}
- (void)setupProgressView
{
    _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 2)];
    [self.scrollView addSubview:_progressView];
    _progressView.progressTintColor = [UIColor redColor];
    _progressView.trackTintColor = [UIColor clearColor];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        if (self.webView.estimatedProgress < 1.0) {
            self.delayTime = 1 - self.webView.estimatedProgress;
            return;
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.progress = 0;
            [self.scrollView.mj_header endRefreshing];
        });
    }
}


- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message{
//    if([message.name isEqualToString:@"share"]) {
//        [self shareShengJingMessageWithImageArray:@[message.body[3]] url:message.body[4] title:message.body[1] contentMessage:message.body[2] type:SSDKContentTypeAuto];
//    }
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
}
/**
 *  在发送请求之前，决定是否跳转
 *
 *  @param webView          实现该代理的webview
 *  @param navigationAction 当前navigation
 *  @param decisionHandler  是否调转block
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//不是首页的视频界面   就跳转下一界面
    if (![(navigationAction.request.URL.absoluteString)hasPrefix:@"http://fuyin.app.inping.com/movie/index.php"]){
//跳转到首页宣传图的H5界面
        LSZPromotionalGraphicDetailsVC * VC = [[LSZPromotionalGraphicDetailsVC alloc]init];
        VC.url =navigationAction.request.URL.absoluteString;
        [self presentViewController:VC animated:YES completion:nil];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
     // 允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
}

//加载完成时调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    self.title = webView.title;
    if ([_link hasPrefix:@"http://fuyin.app.inping.com/"]){
    }
}

// 提示框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示框" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
}

@end
